﻿using B.MESUI.Login.BasicData_UI;
using B.MESUI.Login.Properties;
using B.MESUI.Login.SLY;
using DevExpress.XtraEditors;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static DevExpress.Drawing.Printing.Internal.DXPageSizeInfo;

namespace B.MESUI.Login
{
    public partial class WorkShop : DevExpress.XtraEditors.XtraForm
    {
        private readonly HttpClient httpClient;
        // 用于保存每行的选中状态
        private Dictionary<int, bool> checkStatus = new Dictionary<int, bool>();

        public WorkShop(HttpClient httpClient)
        {
            this.httpClient = httpClient;
        }

        public WorkShop()
        {
            InitializeComponent();
            simpleButton1.Click += SimpleButton1_Click;
            // 添加批量删除按钮事件
            buttonBatchDelete.Click += buttonBatchDelete_Click;
            // 添加复选框列
            AddCheckBoxColumn();
            // 注册Unbound列事件
            gridView1.CustomUnboundColumnData += gridView1_CustomUnboundColumnData;
            // 添加操作列
            AddDeleteButtonColumn();
            LoadData();
        }
        private int pageIndex = 1;
        private int pageSize = 5;
        private int totalCount = 0;
        private int totalPage = 1;
        /// <summary>
        /// 加载数据方法，根据车间代码和名称筛选并显示数据
        /// </summary>
        private async void LoadData()
        {
            // 获取并修剪文本框中的车间代码和名称
            string code = WorkshopCodetextEdit1.Text.Trim();
            string name = workShoptextEdit2.Text.Trim();
           
            // 构造API请求的基础URL
            string url = $"http://39.103.49.30:9982/api/WorkShop/GetAll/GetAll?PageIndex={pageIndex}&PageSize={pageSize}";

          //var result=await BaseMethod.MethodsURL("get",MethodConst.GetPageWorkShop);
            // 根据车间代码和名称构建完整的请求URL
            if (!string.IsNullOrEmpty(code))
                url += $"&WORKSHOP_CODE={code}";
            if (!string.IsNullOrEmpty(name))
                url += $"&WORKSHOP_NAME={name}";
        
            // 使用HttpClient发送请求并处理响应
            using (HttpClient client = new HttpClient())
            {
                

                // 异步获取API响应字符串
                var response = await client.GetStringAsync(url);
                
                // 解析JSON响应
                JObject obj = JObject.Parse(response);
                
                // 提取页面数据并转换为List<GetWorkShopDTO>类型
                var datas = obj["pageDatas"];
                var list = datas.ToObject<List<GetWorkShopDTO>>();
                
                // 将数据源绑定到GridControl并刷新数据源
                gridControl1.DataSource = list;
                gridControl1.RefreshDataSource();

                // 赋值总条数和总页数
                totalCount = obj["totalCount"]?.ToObject<int>() ?? 0;
                totalPage = obj["totalPage"]?.ToObject<int>() ?? 1;
                // 显示总条数
                //labelControl4.Text = totalCount.ToString();
                // 更新分页信息
                UpdatePaginationInfo();
            }
        }

        private void SimpleButton1_Click(object sender, EventArgs e)
        {
            pageIndex = 1; // 查询时重置为第一页
            LoadData();
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            AddWorkShopForm addWorkShop = new AddWorkShopForm();
            if (addWorkShop.ShowDialog() == DialogResult.OK)
            {
                var data = new
                {
                    WORKSHOP_CODE = addWorkShop.WORKSHOP_CODE,
                    WORKSHOP_NAME = addWorkShop.WORKSHOP_NAME,
                    WORKSHOP_DESCRIPTION = addWorkShop.WORKSHOP_DESCRIPTION
                };

                using (HttpClient client = new HttpClient())
                {
                    var content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
                    var response = await client.PostAsync("http://39.103.49.30:9982/api/WorkShop/Add", content);
                    if (response.IsSuccessStatusCode)
                    {
                        MessageBox.Show("新增成功！");
                        LoadData(); // 刷新列表
                    }
                    else
                    {
                        MessageBox.Show("新增失败！");
                    }
                }
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (pageIndex != 1)
            {
                pageIndex = 1;
                LoadData();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (pageIndex > 1)
            {
                pageIndex--;
                LoadData();
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (pageIndex < totalPage)
            {
                pageIndex++;
                LoadData();
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (pageIndex != totalPage)
            {
                pageIndex = totalPage;
                LoadData();
            }
        }

        private void simpleButton1_Click_1(object sender, EventArgs e)
        {
            //查询
            pageIndex = 1; // 重置页码为1
            LoadData();

        }

        private void simpleButton1_Click_2(object sender, EventArgs e)
        {
            //点击查询按钮时，重置页码为1并加载数据
            pageIndex = 1;
            LoadData();
            WorkshopCodetextEdit1.Text = "";
            workShoptextEdit2.Text = "";
        }

        private void AddDeleteButtonColumn()
        {
            if (gridView1.Columns["操作"] == null)
            {
                var col = new DevExpress.XtraGrid.Columns.GridColumn();
                col.Caption = "操作";
                col.Name = "操作";
                col.Visible = true;
                col.VisibleIndex = gridView1.Columns.Count;
                col.Width = 160;

                var btnEdit = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit();
                btnEdit.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor;
                btnEdit.Buttons.Clear();
                btnEdit.Buttons.Add(new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph) { Caption = "修改" });
                btnEdit.Buttons.Add(new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph) { Caption = "删除" });

                btnEdit.ButtonClick += (s, e) =>
                {
                    var id = gridView1.GetFocusedRowCellValue("ID")?.ToString();
                    if (e.Button.Caption == "删除")
                    {
                        if (!string.IsNullOrEmpty(id))
                        {
                            DeleteWorkShop(id);
                        }
                    }
                    else if (e.Button.Caption == "修改")
                    {
                        if (!string.IsNullOrEmpty(id))
                        {
                            EditWorkShop(id);
                        }
                    }
                };
                col.ColumnEdit = btnEdit;
                gridControl1.RepositoryItems.Add(btnEdit);
                gridView1.Columns.Add(col);
            }
        }

        private async void DeleteWorkShop(string id)
        {
            if (MessageBox.Show("确定要删除该车间吗？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                using (HttpClient client = new HttpClient())
                {
                    var response = await client.DeleteAsync($"http://39.103.49.30:9982/api/WorkShop/Delete?Id={id}");
                    if (response.IsSuccessStatusCode)
                    {
                        MessageBox.Show("删除成功！");
                        LoadData();
                    }
                    else
                    {
                        MessageBox.Show("删除失败！");
                    }
                }
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            LoadData();
        }

        // 编辑按钮事件
        private void EditWorkShop(string id)
        {
            var code = gridView1.GetFocusedRowCellValue("WORKSHOP_CODE")?.ToString();
            var name = gridView1.GetFocusedRowCellValue("WORKSHOP_NAME")?.ToString();
            var desc = gridView1.GetFocusedRowCellValue("WORKSHOP_DESCRIPTION")?.ToString();

            EditWorkShopForm editForm = new EditWorkShopForm(id, code, name, desc);
            if (editForm.ShowDialog() == DialogResult.OK)
            {
                UpdateWorkShop(editForm.WorkShopId, editForm.WorkShopCode, editForm.WorkShopName, editForm.WorkShopDesc);
            }
        }

        // 调用后端接口进行修改
        private async void UpdateWorkShop(string id, string code, string name, string desc)
        {
            var data = new
            {
                id = id,
                workshoP_CODE = code,
                workshoP_NAME = name,
                workshoP_DESCRIPTION = desc
            };

            using (HttpClient client = new HttpClient())
            {
                var content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
                var response = await client.PutAsync("http://39.103.49.30:9982/api/WorkShop/Update", content);
                if (response.IsSuccessStatusCode)
                {
                    MessageBox.Show("修改成功！");
                    LoadData();
                }
                else
                {
                    MessageBox.Show("修改失败！");
                }
            }
        }

        private void AddCheckBoxColumn()
        {
            if (gridView1.Columns["选择"] == null)
            {
                var checkCol = new DevExpress.XtraGrid.Columns.GridColumn();
                checkCol.Caption = "选择";
                checkCol.Name = "选择";
                checkCol.Visible = true;
                checkCol.VisibleIndex = 0;
                checkCol.Width = 40;
                checkCol.FieldName = "isChecked";
                checkCol.UnboundType = DevExpress.Data.UnboundColumnType.Boolean;
                checkCol.OptionsColumn.AllowEdit = true;
                var checkEdit = new DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit();
                checkCol.ColumnEdit = checkEdit;
                gridControl1.RepositoryItems.Add(checkEdit);
                gridView1.Columns.Insert(0, checkCol);
            }
        }

        // 实现Unbound列多选支持
        private void gridView1_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if (e.Column.FieldName == "isChecked")
            {
                if (e.IsGetData)
                {
                    if (checkStatus.ContainsKey(e.ListSourceRowIndex))
                        e.Value = checkStatus[e.ListSourceRowIndex];
                    else
                        e.Value = false;
                }
                if (e.IsSetData)
                {
                    checkStatus[e.ListSourceRowIndex] = (bool)e.Value;
                }
            }
        }

        private async void buttonBatchDelete_Click(object sender, EventArgs e)
        {
            // 获取所有选中的ID
            var ids = new List<string>();
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                bool isChecked = false;
                if (checkStatus.ContainsKey(i))
                    isChecked = checkStatus[i];
                if (isChecked)
                {
                    var id = gridView1.GetRowCellValue(i, "ID")?.ToString();
                    if (!string.IsNullOrEmpty(id))
                        ids.Add(id);
                }
            }
            if (ids.Count == 0)
            {
                MessageBox.Show("请先选择要删除的数据！");
                return;
            }
            if (MessageBox.Show($"确定要批量删除选中的{ids.Count}条数据吗？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                using (HttpClient client = new HttpClient())
                {
                    var url = $"http://39.103.49.30:9982/api/WorkShop/DeleteList?Ids={string.Join(",", ids)}";
                    var response = await client.DeleteAsync(url);
                    if (response.IsSuccessStatusCode)
                    {
                        MessageBox.Show("批量删除成功！");
                        checkStatus.Clear(); // 清空选中状态
                        LoadData();
                    }
                    else
                    {
                        MessageBox.Show("批量删除失败！");
                    }
                }
            }
        }

        private void UpdatePaginationInfo()
        {
            // 假设labelControl7显示"第X/Y页 共Z条"
            labelControl7.Text = $"第{pageIndex} / {totalPage}页 共{totalCount}条";
            // 控制分页按钮可用性
            button4.Enabled = pageIndex > 1 && totalPage > 0; // 首页
            button2.Enabled = pageIndex > 1 && totalPage > 0; // 上一页
            button3.Enabled = pageIndex < totalPage && totalPage > 0; // 下一页
            button5.Enabled = pageIndex < totalPage && totalPage > 0; // 尾页
        }

        private void simpleButton3_Click(object sender, EventArgs e)
        {
            int jumpPage = 1;
            if (int.TryParse(textBoxJump.Text, out jumpPage))
            {
                if (jumpPage >= 1 && jumpPage <= totalPage)
                {
                    pageIndex = jumpPage;
                    LoadData();
                }
                else
                {
                    MessageBox.Show($"请输入1到{totalPage}之间的页码！");
                }
            }
            else
            {
                MessageBox.Show("请输入正确的页码！");
            }
        }
        private async  void simpleButton4_Click(object sender, EventArgs e)
        {
            // 调用后端导出接口，假设接口为 /api/WorkShop/Export
            string url = "http://39.103.49.30:9982/api/WorkShop/Export/export";
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    var response = await client.GetAsync(url);
                    if (response.IsSuccessStatusCode)
                    {
                        var bytes = await response.Content.ReadAsByteArrayAsync();
                        using (SaveFileDialog sfd = new SaveFileDialog())
                        {
                            sfd.Filter = "Excel文件|*.xlsx|所有文件|*.*";
                            sfd.FileName = "车间信息导出.xlsx";
                            if (sfd.ShowDialog() == DialogResult.OK)
                            {
                                System.IO.File.WriteAllBytes(sfd.FileName, bytes);
                                MessageBox.Show("导出成功！");
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("导出失败！");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("导出异常：" + ex.Message);
                }
            }
        }

      
    }
}